 // 给你一个链表的头节点 head ，旋转链表，将链表每个节点向右移动 k 个位置。

      // 输入：head = [1,2,3,4,5], k = 2
      // 输出：[4,5,1,2,3]

      // 输入：head = [0,1,2], k = 4
      // 输出：[2,0,1]

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

class ListNode {
    val: number
    next: ListNode | null
    constructor(val?: number, next?: ListNode | null) {
        this.val = (val===undefined ? 0 : val)
        this.next = (next===undefined ? null : next)
    }
}

function rotateRight(head: ListNode | null, k: number): ListNode | null {
  if(!head || !head.next || k === 0) {
    return head
  }
  let len = 1
  let link: ListNode | null = head ?? null
  while(link.next) {
    link = link.next
    len++
  }
  let n = len - k % len
  if (n === len) {
    return head
  }
  link.next = head
  while(n) {
    link = link?.next || null
    n--
  }
  head = link?.next || null
  if (link?.next) {
    link.next = null
  }
  return head
};

const head = new ListNode(0)
const sec = new ListNode(1)
const a = new ListNode(2)
head.next = sec
sec.next = a
console.log(rotateRight(head, 4))